package com.myk.game.lib.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.myk.game.lib.R;

/**
 * 自定义开关状态控件，可以设置开关状态的文字和图片，若必要属性没有设置，默认效果和CheckBox一样
 */
public class ToggleBox extends androidx.appcompat.widget.AppCompatCheckBox {

    private CharSequence mTextOn;
    private CharSequence mTextOff;
    private Drawable mDrawableOn;
    private Drawable mDrawableOff;

    public ToggleBox(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ToggleBox(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.ToggleBox);
        mTextOn = mTypedArray.getString(R.styleable.ToggleBox_text_on);
        mTextOff = mTypedArray.getString(R.styleable.ToggleBox_text_off);
        mDrawableOn = mTypedArray.getDrawable(R.styleable.ToggleBox_drawable_on);
        mDrawableOff = mTypedArray.getDrawable(R.styleable.ToggleBox_drawable_off);
        syncTextState();
        syncDrawableState();
        mTypedArray.recycle();
    }

    @Override
    public void setChecked(boolean checked) {
        super.setChecked(checked);
        syncTextState();
        syncDrawableState();
    }

    private void syncTextState() {
        boolean checked = isChecked();
        if (checked && mTextOn != null) {
            setText(mTextOn);
        }
        else if (!checked && mTextOff != null) {
            setText(mTextOff);
        }
    }

    private void syncDrawableState() {
        boolean checked = isChecked();
        if (checked && mDrawableOn != null) {
            setButtonDrawable(null);
            setBackground(mDrawableOn);
        }
        else if (!checked && mDrawableOff != null) {
            setButtonDrawable(null);
            setBackground(mDrawableOff);
        }
    }
}
